// circle/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    datas: [],
    action: true,
    plnum: '',
    imgUrls: [
      'https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640',
      'https://images.unsplash.com/photo-1551214012-84f95e060dee?w=640',
      'https://images.unsplash.com/photo-1551446591-142875a901a1?w=640'
    ],
    indicatorDots: "#000",
    autoplay: true,
    interval: 5000,
    duration: 2000,
    img: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        // console.log('[云函数] [login] user openid: ', res.result.openid)
        wx.setStorage({
          key: 'openId',
          data: res.result.openid,
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)

      }
    })

    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              wx.setStorage({
                key: 'login-Message',
                data: res.userInfo
              })
            }
          })
        } else if (res.authSetting['scope.userInfo'] === false) {
          wx.openSetting({
            success: res => {
              console.log(res)
            },
            fail: res => {
              console.log(res)
            }
          })
        } else {
          wx.getUserInfo({
            success: res => {
              console.log(res)
            },
            fail: res => {
              console.log(res)
              wx.openSetting({
                success: res => {
                  console.log(res)
                },
                fail: res => {
                  console.log(res)
                }
              })
            }
          })
        }
      },
      fail: res => {
        console.log(res)
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.getdata()
    this.getindexdata()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },


  // 排序点击事件
  sort: function() {
    wx.showActionSheet({
      itemList: ['按发帖时间', '按最后回帖时间'],
      success(res) {
        console.log(res.tapIndex)
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },

  // 跳转详情点击事件
  jompXQ: function(e) {
    var data = e.currentTarget.dataset.index;
    wx.setStorage({
      key: 'detail',
      data: data,
    })
    console.log()
    wx.navigateTo({
      url: '../particulars/particulars'
    })
  },


  // 获取数据
  getdata: function() {
    const db = wx.cloud.database()
    db.collection('pinglun').where({
      // _openid: 'xxx' // 填入当前用户 openid
    }).get({
      success: (res) => {
        this.setData({
          plnum: res.data.length
        })
      }
    })
  },

  // 获取首页数据
  getindexdata: function() {
    const db = wx.cloud.database()
    db.collection('news').where({
      // _openid: 'xxx' // 填入当前用户 openid
    }).get({
      success: (res) => {
        var olddata = res.data;
        // console.log(olddata)
        for (var i = 0; i < olddata.length; i++) {
          var aa = olddata[i]['imgs'];
          var newpath = [];
          wx.cloud.getTempFileURL({
            fileList: [{
              fileID: aa[0],
              maxAge: 60 * 60,
            }]
          }).then(res => {
            var index = res.fileList[0].tempFileURL.lastIndexOf("\/");
            var pathBefore = res.fileList[0].tempFileURL.substring(0, index + 1);
            for (var j = 0; j < aa.length; j++) {
              var imgAfter = aa[j].substring(aa[j].lastIndexOf("/") + 1);
              newpath.push(pathBefore + imgAfter);
            }
            // console.log(newpath)
            olddata[i-1]['imgs'] = newpath;
          }).catch(error => { })
        }
        // console.log(olddata)
        // return;
        this.setData({
          datas: olddata
        })
        // console.log(this.data.datas)

      }
    })
  },
  getimgpath: function(path) {
    var that = this;
    wx.cloud.getTempFileURL({
      fileList: [path],
      success: res => {
        console.log(res.fileList[0].tempFileURL)
        that.setData({
          quimgup: res.fileList[0].tempFileURL
        });
      },
      fail: err => {
        // handle error
      }
    })
  },
  menvEvent: function() {
    this.setData({
      action: true
    })
    console.log(this.data.action)
  },
  guanzhuEvent: function() {
    this.setData({
      action: false
    })
  }
})